package com.tiger.cloud.controller.crm;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.auth0.jwt.Token;
import com.tiger.cloud.auth0.jwt.TokenGenerator;
import com.tiger.cloud.auth0.jwt.exceptions.JWTCreationException;
import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.common.token.PasswordHashUtil;
import com.tiger.cloud.enums.AppSmsType;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.enums.UserStatusEnum;
import com.tiger.cloud.filter.CurrentUserId;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.form.AppSmsMessages;
import com.tiger.cloud.form.CompanyForm;
import com.tiger.cloud.form.SysDictSmall;
import com.tiger.cloud.form.UserLoginForm;
import com.tiger.cloud.model.crm.AppSms;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.crm.UserCompanyInfo;
import com.tiger.cloud.model.crm.UserInfo;
import com.tiger.cloud.service.crm.IAppSmsService;
import com.tiger.cloud.service.crm.IUserCompanyInfoService;
import com.tiger.cloud.service.crm.IUserInfoService;
import com.tiger.cloud.service.crm.IUserService;
import com.tiger.cloud.service.system.CommonDict;
import com.tiger.cloud.util.DateTimeUtil;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.MagicConstants;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户管理
 */
@Controller
@RequestMapping(value = "user")
@Api(value = "用户管理",tags = "用户")
public class UserController extends BaseController {

	private static final Logger logger=Logger.getLogger(UserController.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IAppSmsService appSmsService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IUserCompanyInfoService userCompanyInfoService;
	
	/**
	 * 获取列表默认值
	 */
	@IgnoreAuth
	@RequestMapping(value = "getDefaultFileds", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取列表默认值",notes = "获取列表默认值")
	public Response getDefaultFileds(){
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		return ResponseUtil.ok(values);
	}
	
	@RequestMapping(value = "get", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取默认用户信息",notes = "获取默认用户信息")
	public Response get(@CurrentUserId Long userId){
		UserInfo userInfo=new UserInfo();
		userInfo.setIsDelete(DeleteEnum.NOMAIL);
		userInfo.setUserId(userId);
		UserInfo userInfo2=userInfoService.findOne(userInfo);
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("userInfo", userInfo2);
		maps.put("values", values);
		return ResponseUtil.ok(maps);
	}
	
	
	/**
	 * 忘记密码
	 * @param request
	 * @param loginId
	 * @param password
	 */
	@IgnoreAuth
	@RequestMapping(value = "forgotPassword", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "忘记密码",notes = "忘记密码")
	public Response forgotPassword(@CurrentUserId String userId, @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginForm.getPhone())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		//发送验证码
		AppSms appVerifCode=new AppSms();
		appVerifCode.setPhone(userLoginForm.getPhone());
		appVerifCode.setOrderBy("create_time desc");
		AppSms findAppVerifCode=appSmsService.findOne(appVerifCode);
		if(findAppVerifCode==null){
			return ResponseUtil.error("无效的验证码");
		}
		if(DateTimeUtil.getMillisecondsOfTwoDate(findAppVerifCode.getActiveTime(), DateTimeUtil.getSystemDate())<0){
			return ResponseUtil.error("验证码已过期");
		}
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		Map<String, Object> findUser = new HashMap<String, Object>();
		findUser.put("login_id", userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {
			return ResponseUtil.error("用户处于审核中,暂时无法操作");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			return ResponseUtil.error("用户处于冻结中,暂时无法操作");
		}
		//更新密码
		User updateUser=new User();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginForm.getNewPassword()));
		userService.update(updateUser);
		return ResponseUtil.ok();
	}
	
	/**
	 * 处理用户注册
	 */
	@IgnoreAuth
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "处理用户注册",notes = "处理用户注册")
	public Response register(  @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		//注册完成,此用户处于待审核阶段
		User user= userService.register(userLoginForm.getLoginId(), userLoginForm.getPassword());
		if (user==null) {
			return ResponseUtil.error("注册失败,密码无效!");
		}
		return ResponseUtil.ok();
	}
	
	/**
	 * 处理用户注册--->完善用户企业信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "authCompany", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "完善用户注册企业信息",notes = "处理用户注册--->完善用户企业信息")
	public Response authCompany(@CurrentUserId Long userId,  @RequestBody CompanyForm companyForm) {
		if(StringUtils.isEmpty(companyForm.getBusinessCard())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if(StringUtils.isEmpty(companyForm.getCompanyName())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if(StringUtils.isEmpty(companyForm.getHeadImage())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		companyForm.setUserId(userId);
		UserCompanyInfo userCompanyInfo=userCompanyInfoService.register(companyForm);
		if (userCompanyInfo==null) {
			return ResponseUtil.error("日期选择无效,请重新选择!");
		}
		return ResponseUtil.ok(userCompanyInfo);
	}
	
	/**
	 * 处理用户登陆
	 */
	@IgnoreAuth
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户登陆",notes = "处理用户登陆")
	public Response login(  @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		Map<String, Object> findUser = new HashMap<String, Object>();
		findUser.put("login_id", userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {//0:待审核、1:正常、2:冻结
			return ResponseUtil.error("用户正在审核中,暂时无法登陆");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {//0:待审核、1:正常、2:冻结
			return ResponseUtil.error("用户正在冻结中,暂时无法登陆");
		}
		if (!PasswordHashUtil.validatePassword(userLoginForm.getPassword(), user.getPassword())) {
			return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID);
		}
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put( MagicConstants.SESSION_USER_ID, user.getId());
		Token token=TokenGenerator.create(claims);
		return ResponseUtil.ok(token);
	}

	@RequestMapping(value = "sendVerifCode", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "发送验证码",notes = "发送验证码")
	public Response sendVerifCode(@RequestBody UserLoginForm userLoginForm) {
		if(StringUtils.isEmpty(userLoginForm.getLoginId())){
			User findUser = new User();
			findUser.setLoginId(userLoginForm.getLoginId());
			User sysUser = userService.findOne(findUser);
			if (sysUser == null) {
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
			}
		}
		String code = RandomStringUtils.randomNumeric(4);
		appSmsService.sendToUID(AppSmsMessages.getMsg(AppSmsMessages.REGISTER_MSG, code), userLoginForm.getPhone(), AppSmsType.VERIF_CODE, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(),10));
		return ResponseUtil.ok();
	}

	/**
	 * 更新用户基本信息
	 * @param userId
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新用户基本信息",notes = "更新用户基本信息")
	public Response update(@CurrentUserId Long userId,User user){
		if (user==null||user.getId()!=null) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID);
		}
		User updateUser=userService.get(userId);
		if (updateUser==null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
		}
		user.setId(userId);
		int updateCount=userService.update(user);
		return ResponseUtil.ok(updateCount==1?true:false);
	}
	
}